package com.gzbsoft.sc.modules.app.resolver;
import com.gzbsoft.sc.common.annotation.LoginUser;
import com.gzbsoft.sc.modules.app.interceptor.AuthorizationInterceptor;
import com.gzbsoft.sc.modules.app.service.JxUserService;
import com.gzbsoft.sc.modules.sys.entity.JxUser;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private final JxUserService userService;
    public LoginUserHandlerMethodArgumentResolver(JxUserService userService) {
        this.userService = userService;
    }
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(JxUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        //获取用户信息
        return userService.getById((Long) object).orElseGet(JxUser::new);
    }
}
